package com.sneakxy.cloudbase.platform.utils.web;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

/**
 * JSON转换拓展
 * @author 潜行的虚影
 *
 */
public class JSONExt {

	/**
	 * 自定义转换
	 * @param <T>
	 * @param json
	 * @param clazz
	 * @param propertyMatchMap 自定义字段名称key:clazz字段名称，value：json字段名
	 * @return
	 */
	public static <T> T parse(String json, Class<T> clazz, Map<String, String> propertyMatchMap) {
		JSONObject obj = JSON.parseObject(json);
		T result = obj.to(clazz);
		propertyMatchMap.forEach((key, value) -> {
			if(StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
				Field field = FieldUtils.getField(clazz, key, true);
				if(field != null) {
					try {
						FieldUtils.writeField(field, result, obj.getObject(value, field.getType()), true);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				} else {
					String methodName = StringUtilsExt.setter(key);
					Method setter = MethodUtilsExt.findFirstMethod(clazz, methodName, NumberUtils.INTEGER_ONE);
					if(setter != null) {
						boolean isAccessible = setter.isAccessible();
						try {
							setter.setAccessible(true);
							setter.invoke(result, obj.getObject(value, setter.getParameterTypes()[0]));
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						} finally {
							setter.setAccessible(isAccessible);
						}
					}
				}
			}
		});
		return result;
	}
	
}
